﻿"use strict";
define(["admin/app", "service/admin/categoryService", "ui.file.manage", "ui.sortable"], function (app) {
    app.controller("categoryController", function ($scope, $state, $stateParams, $location, utils, categoryService, w5cValidator) {
        $scope.psdisabled = false;

        var methods = {
            search: function () {
                categoryService.gets({ name: $scope.name }).success(function (response) {
                    $scope.list = response.data;
                    if ($stateParams.action != undefined) {
                        $scope.list.splice(0, 0, { id: 0, name: '请选择上级分组' });
                    }
                });
            },
            edit: function () {
                if ($stateParams.id > 0) {
                    categoryService.get({ id: $stateParams.id }).success(function (response) { $scope.model = response.data; });
                    $scope.breadcrumb = '编辑';
                }
                else {
                    $scope.model = { id: 0 };
                    $scope.breadcrumb = '新增';
                }
                w5cValidator.setRules({
                    name: { required: '请填写分组名称' }
                });
            },
            goBack: function () {
                history.back();
            },
            save: function () {
                var model = $scope.model;
                $scope.psdisabled = true;
                categoryService.save(model).success(function (response) {
                    utils.notify(response.result_msg, response.result_code == 1000 ? "success" : "warning");
                    if (response.result_code == 1000)
                        methods.goBack();
                    else
                        $scope.psdisabled = false;
                }).error(function () { $scope.psdisabled = false; });

            },
            remove: function (model) {
                var modal = utils.confirm({ msg: "是否需要删除当前项目", ok: "确定", cancel: "取消" });
                modal.result.then(function () {
                    categoryService.delete(model.id).success(function (response) {
                        utils.notify(response.result_msg, response.result_code == 1000 ? "success" : "warning");
                        if (response.result_code == 1000)
                            utils.remove($scope.model, model);
                    })
                })
            }
        }
        angular.extend($scope, methods);

        methods.search();
        if ($stateParams.action != undefined) {
            methods.edit();
        }
    });
});